<?php
/**
 * IG_Controller_Plugin_Common
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Common.php 1127 2012-01-06 11:11:21Z mmxie $
 */
class IG_Controller_Plugin_Common extends Zend_Controller_Plugin_Abstract
{

    protected $_accessLogDeny = array(
        'default.index.index',
        'default.install.index',
        'default.service'
    );

    /**
     * @return Zend_view
     */
    protected function _getView()
    {
        return Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')->view;
    }

    /**
     * 产品常量定义
     */
    protected function _defineProduct()
    {
        if (!($product = $this->getRequest()->getParam('PRODUCT'))) {
            $host = $this->getRequest()->getHeader('HOST');
            $product = str_replace('_', '.', implode(explode('.', $host, -3)));
        } else {
            $_COOKIE['PRODUCT'] = $product;
        }
        if ($product == null) {
            $appliaction = Zend_Registry::get('lvan_application');
            $product = $appliaction['product']['key'];
        }
        define('PRODUCT', strtoupper($product));
    }

    /**
     *
     */
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        $this->_defineProduct();
        $this->_assessLog($request);

        //如果是 AJAX提交, 不执行视图操作
        if ($request->isXmlHttpRequest() || $this->_inUnload()) {
            Zend_Layout::getMvcInstance()->disableLayout();
            return ;
        }
        $this->_jquery($request);
        $this->_view($request);
    }

    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        //如果是 AJAX提交, 不执行视图操作
        if ($request->isXmlHttpRequest()) {
            if (!$request->isPost()) { // get 方式,
                echo $this->_loadScript();
            }
            return ;
        }

        //如果启用布局,检测是否有该动作的JS,有则加载

        if (Zend_Layout::getMvcInstance()->isEnabled()) {
            $this->_loadScript();
        }
    }

    protected function _loadScript()
    {
        $request = $this->getRequest();
        $jsUrl = '/js'
               . '/' . $request->getModuleName()
               . '/' . $request->getControllerName()
               . '/' . $request->getActionName()
               . '.js';
        if (file_exists(APPLICATION_PATH . '/../public' . $jsUrl)) {
            $this->_getView()->headScript()
                             ->appendFile($jsUrl);
            return $this->_getView()->headScript();
        }
    }

    /**
     * 视图基础配置, 如果是 AJAX 提交或为 Web Service 就不加载
     * @param Zend_Controller_Request_Abstract $request
     */
    protected function _view(Zend_Controller_Request_Abstract $request)
    {
        $view    = $this->_getView();
        $options = Zend_Registry::get('lvan_options');

        $view->assign('theme', isset($options->theme) ? $options->theme : 'default');
        $view->headTitle()->getContainer()->setSeparator('::');
        $view->headTitle()->append(
            isset($options->title) ? $options->title : ''
        );

        //添加helper
        $helperDirs = IG_Filesystem_Dir::getDirectories(
            APPLICATION_PATH . '/../library/IG/View/Helper/'
        );

        if (is_array($helperDirs)) {
            foreach ($helperDirs as $dir) {
                $view->addHelperPath('IG/View/Helper/' . ucfirst($dir),
                                     'IG_View_Helper_' . ucfirst($dir));
            }
        }
    }

    /**
     * ZendX Jquery 配置
     * 如果是WEB SERVICE 就不加载
     */
    protected function _jquery(Zend_Controller_Request_Abstract $request)
    {
        $front = Zend_Controller_Front::getInstance();
        $bootstrap = $front->getParam('bootstrap');
        $bootstrap->registerPluginResource('Jquery', $bootstrap->getOption('ZendX'))
                  ->bootstrap('Jquery')
                  ;
    }

    /**
     * 加载访问日志
     * @param Zend_Controller_Request_Abstract $request
     */
    protected function _assessLog(Zend_Controller_Request_Abstract $request)
    {
        $action = $request->getModuleName() . '.'
                . $request->getControllerName() . '.'
                . $request->getActionName();

        foreach ($this->_accessLogDeny as $deny) {
            if (strpos($action, $deny) !== false) {
                return ;
            }
        }

        $auth = Zend_Auth::getInstance();
        $employeeId = $auth->hasIdentity() ? $auth->getIdentity()->getEmployeeId() : 0;

        $params = $request->getParams();
        unset($params['module'], $params['controller'], $params['action']);

        if (isset($params['password'])) {
            $params['password'] = '[' . strlen($params['password']) . ']';
        }

        //保存访问日志
        $accessLog = new System_Model_AccessLog();
        $accessLog->setEmployeeId($employeeId)
                  ->setUrl($action)
                  ->setParams(substr(http_build_query($params), 0, 255))
                  ->save()
                  ;
    }

    protected function _inUnload()
    {
        $request = $this->getRequest();
        $action  = $request->getModuleName() . '.'
                 . $request->getControllerName();
        return in_array($action, array('default.service')) ||
               $request->getModuleName() == 'api';
    }
}